﻿using Microsoft.SharePoint.ApplicationPages.Calendar.RecurrenceRule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindStyle.SPCalendar.Pattern
{
    public class WeeklyPattern : IPattern
    {
        public int Frequency { get; set; }
        public DaysOfWeek Days { get; set; }

        public WeeklyPattern()
        {
            this.Frequency = 1;
            this.Days = Utility.ParseDayOfWeek(DateTime.Today.DayOfWeek);
        }

        public string ToXML()
        {
            return string.Format("<weekly {1}{2}{3}{4}{5}{6}{7}weekFrequency=\"{0}\" />",
                this.Frequency,
                this.Days.HasFlag(DaysOfWeek.Monday) ? "mo=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Tuesday) ? "tu=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Wednesday) ? "we=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Thursday) ? "th=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Friday) ? "fr=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Saturday) ? "sa=\"TRUE\" " : string.Empty,
                this.Days.HasFlag(DaysOfWeek.Sunday) ? "su=\"TRUE\" " : string.Empty);
        }


        public void FromRule(RecurrenceRule recurrence)
        {
            this.Days = DaysOfWeek.None;
            this.Frequency = recurrence.Frequency;

            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Monday))
                this.Days = this.Days | DaysOfWeek.Monday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Tuesday))
                this.Days = this.Days | DaysOfWeek.Tuesday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Wednesday))
                this.Days = this.Days | DaysOfWeek.Wednesday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Thursday))
                this.Days = this.Days | DaysOfWeek.Thursday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Friday))
                this.Days = this.Days | DaysOfWeek.Friday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Saturday))
                this.Days = this.Days | DaysOfWeek.Saturday;
            if (recurrence.DaysOfWeek.Contains(DayOfWeek.Sunday))
                this.Days = this.Days | DaysOfWeek.Sunday;
        }
    }

}
